//
//  OrderStateVC.swift
//  Employee
//
//  Created by swordjoy on 2017/3/24.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import SwiftyJSON
import MJRefresh
import Moya

enum OrderStateVCType {
    case home
    case all
    case timeOut
    case accepting
    case submit
    case wait
}

class OrderStateVC: BaseVC {
    var parentVC: UIViewController!
    var type: OrderStateVCType!

    fileprivate lazy var noDataV: NoDataV? = {
        let noDataV = NoDataV(frame: self.tableView.bounds)
        noDataV.image = UIImage(named: "bg-01")!
        
        var typeString = ""
        
        if .all == self.type { typeString = "没有全部工单"}
        else if .home == self.type { typeString = "太好啦~"; noDataV.bottomTipText = "老板没有安排工作！"}
        else if .accepting == self.type { typeString = "没有受理工单" }
        else if .submit == self.type { typeString = "没有提交工单" }
        else if .wait == self.type { typeString = "没有待接工单" }
        noDataV.topTipText = typeString
        self.tableView.addSubview(noDataV)
        
        return noDataV
    }()
    fileprivate var workOrders: [WorkOrder] = []
    fileprivate var page = PageModel()
    fileprivate var tableView: UITableView!
    fileprivate lazy var netWorkView: UIButton = {
        let btn = UIButton()
        btn.isEnabled = false
        btn.isHidden = true
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        self.view.addSubview(btn)
        btn.frame = CGRect(x: 0, y: -44, width: UIScreen.width, height: 44.0)
        btn.backgroundColor = UIColor.hex("#FB5F5F")
        btn.setTitle("当前网络不可用，请检查您的网络设置", for: .disabled)
        btn.setTitleColor(UIColor.white, for: .disabled)
        btn.setImage(UIImage(named:"network_fail"), for: .disabled)
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0)
        
        return btn
    }()
    fileprivate var headerCancle: Cancellable?
    fileprivate var reach: Reachability!

    override func viewDidLoad() {
    super.viewDidLoad()
        view.backgroundColor = GlobalConfig.BGWhiteColor

        // 初始化
        self.reach = Reachability.forInternetConnection()
        // 添加通知
        NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(noti:)), name: NSNotification.Name.reachabilityChanged, object: nil)
        self.reach!.startNotifier()
        
        create()
        
        //判断连接状态
        if self.reach.currentReachabilityStatus() == NotReachable {
            self.netWorkView.isHidden = false
            changeTableviewFrame(flag: true)
            UIView.animate(withDuration: 0.2, animations: {
                self.netWorkView.mj_origin.y = 0
            })
        }
        
    }
  
    func reachabilityChanged(noti:NSNotification) {
        self.netWorkView.isHidden = self.reach.currentReachabilityStatus() != NotReachable
        UIView.animate(withDuration: 0.2, animations: {
            self.netWorkView.mj_origin.y = !self.netWorkView.isHidden ? 0 : -44
        })
        changeTableviewFrame(flag: !self.netWorkView.isHidden)
    }
    func changeTableviewFrame(flag: Bool = false) {
        UIView.animate(withDuration: 0.2) {
            self.tableView.mj_origin.y = flag ? self.netWorkView.mj_size.height : 0
        }
        let height = .home == type ? UIScreen.noNavBarHeight : UIScreen.noNavBarHeight - 44.0
        self.tableView.mj_size.height = flag ? height-netWorkView.mj_size.height : height
    }
}

// MARK: - interface 

extension OrderStateVC {
    /// 外面第一次进来刷新数据
    func updateData() {
        headerRefresh()
    }
  
    func dismiss() {
        headerCancle?.cancel()
        tableView.mj_header.endRefreshing()
    }
}

// MARK: - fileprivate

extension OrderStateVC {
  
  // 最后一个table footer改变
  fileprivate func lastPage() {
  
    tableView.mj_footer.isHidden = true
    
  }
  
  @objc fileprivate func headerRefresh() {
    
    var typeString = ""
    
    
    if .all == type {
      typeString = "all"
    } else if .accepting == type {
      typeString = "accepted"
    } else if .submit == type {
      typeString = "commited"
    } else if .wait == type {
      typeString = "untreated"
    } else if .home == type {
        typeString = "home"
    }
    
    SJApp.showHUD()
    headerCancle = WorkorderRequest.shared.getOrder(status: typeString, pagepn: page.headerPage, success: { (orders, pageModel) in
      SJApp.hideHUD()
      self.tableView.mj_header.endRefreshing()
      
      if orders.isEmpty {
        self.noDataV?.isHidden = false
        return
      } else {
        if let _ = self.noDataV { self.noDataV?.isHidden = true }
      }
      
      self.workOrders = orders
      self.page = pageModel
      
      self.tableView.reloadData()
      
      self.tableView.mj_footer.isHidden = false
      // 分页判断
      if !self.page.hasNextPage { self.lastPage() }
      
    }, failure: { 
      SJApp.hideHUD()
      self.tableView.mj_header.endRefreshing()
      
    })
    
    
  }
  
  @objc fileprivate func footerRefresh() {
    
    var typeString = ""
    
    if .all == type {
      typeString = "all"
    } else if .accepting == type {
      typeString = "accepted"
    } else if .submit == type {
      typeString = "commited"
    } else if .wait == type {
      typeString = "untreated"
    } else if .home == type {
        typeString = "home"
    }
    
    let _ = WorkorderRequest.shared.getOrder(status: typeString, pagepn: page.nextPage, success: { (orders, pageModel) in
      
      self.workOrders += orders
      self.page = pageModel
      
      self.tableView.mj_footer.isHidden = false
      // 分页判断
      if !self.page.hasNextPage {
        self.lastPage()
      } else {
        self.tableView.mj_footer.endRefreshing()
      }
      
      self.tableView.reloadData()
      
    }) { 
      self.tableView.mj_footer.endRefreshing()
    }
    
  }
  
  fileprivate func create() {
    
    tableView = UITableView()
    tableView.backgroundColor = GlobalConfig.BGWhiteColor
    tableView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height:  .home == type ? UIScreen.noNavBarHeight : UIScreen.noNavBarHeight - 44.0)
    tableView.delegate = self
    tableView.dataSource = self
    tableView.separatorStyle = .none
    tableView.register(WorkOrderCell.self, forCellReuseIdentifier: WorkOrderCell.identifier)
    
    let footerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
    footerView.backgroundColor = GlobalConfig.BGWhiteColor
    tableView.tableFooterView = footerView
    
    let headerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 4))
    headerView.backgroundColor = GlobalConfig.BGWhiteColor
    tableView.tableHeaderView = headerView
    
    tableView.mj_header = CustomRefreshHeader(refreshingTarget: self, refreshingAction: #selector(headerRefresh))
    tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(footerRefresh))
    tableView.mj_footer.isHidden = true
    
    view.insertSubview(tableView, belowSubview: netWorkView)
   
  }
  
}

// MARK: - UITableViewDataSource

extension OrderStateVC : UITableViewDataSource {
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    return workOrders.count
    
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cell = tableView.dequeueReusableCell(withIdentifier: WorkOrderCell.identifier) as! WorkOrderCell
    cell.model = workOrders[indexPath.row]
    return cell
    
  }
  
}

// MARK: - UITableViewDelegate

extension OrderStateVC : UITableViewDelegate {
  
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return WorkOrderCell.height(with: workOrders[indexPath.row])
  }
  
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
    let vc = OrderDetailBaseVC()
    vc.orderId = workOrders[indexPath.row].id
    vc.parentVC = parentVC
    vc.orderStatus = OrderHelper.getType(order: workOrders[indexPath.row])
    parentVC.navigationController?.pushViewController(vc, animated: true)
    
  }
  
  func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    
    let fixView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 1))
    fixView.backgroundColor = GlobalConfig.BGWhiteColor
    return fixView
    
  }
  
  func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 1
  }
  
}
